<?php
/**
 * 订单管理
 * User: 梁晓伟  lxw11109@gmail.com
 * Date: 2017-09-07
 * Time: 19:17
 */

namespace App\Http\Controllers\Api\V1\Front\Mall;


use App\Http\Controllers\Controller;
use App\Libs\Contracts\PayMent\AliPay\AliMobile;
use App\Libs\Contracts\PayMent\AliPay\AliWeb;
use App\Libs\Contracts\PayMent\AliPay\App\aop\AliApp;
use App\Libs\Contracts\PayMent\Wxpay\JsApiNativePay;
use App\Libs\Contracts\PayMent\Wxpay\NativePay;
use App\Libs\Contracts\PayMent\Wxpay\Refund;
use App\Libs\Contracts\PayMent\Wxpay\ScanNativePay;
use App\Libs\Contracts\PayMent\Wxpay\WxPayApi;
use App\Models\Address;
use App\Models\Commodity;
use App\Models\CommoditySku;
use App\Models\DeviceSetting;
use App\Models\Order;
use App\Models\OrderDetail;
use App\Models\OrderRefund;
use App\Models\OrderRefundLog;
use App\Models\Setting;
use App\Models\User;
use App\Models\UserCoupon;
use App\Models\UserScoreLog;
use App\Services\Front\AreaTotalService;
use App\Services\Front\OrderService1;
use App\Services\Front\UserScoreService;
use App\Services\Manager\RefundService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Monolog\Handler\IFTTTHandler;
use Symfony\Component\Routing\Tests\Matcher\Dumper\renamed;

class OrderController extends Controller
{

    public function order(Request $request)
    {
        $addressId = $request->addressId;
        $userId = $request->USERID;
        $amount = $request->amount;
        $orderType = $request->orderType ? $request->orderType : "WX";
        $remark = $request->remark;
        if (!$addressId) {
            return $this->apiResponse('', config('errorCode.NOT_EXIST_ADDRESS'));
        }
        if (!$amount || !$orderType) {
            return $this->apiResponse('', config('errorCode.INVALID_REQ_PARAMS'));
        }
        $address = Address::find($addressId);
        if (!$address) {
            return $this->apiResponse('', config('errorCode.NOT_ADDRESS'));
        }
        $good = Commodity::find(1);
        $goodImage = explode(";", $good['goodImage']);
        $order['orderNo'] = getOrderSn("");
        $order['remark'] = $remark;
        $order['goodIcon'] = $userId;
        $order['userId'] = $userId;
        $order['goodIcon'] = $goodImage[0];
        $order['goodTitle'] = $good['goodTitle'];
        $order['goodPrice'] = $good['goodPrice'];
        $order['totalPrice'] = $good['goodPrice'] * $amount;
        $order['amount'] = $amount;

        $order['reciverName'] = $address['reciverName'];
        $order['phone'] = $address['phone'];
        $order['province'] = $address['province'];
        $order['city'] = $address['city'];
        $order['area'] = $address['area'];
        $order['detail'] = $address['detail'];
        $order['createTime'] = date('Y-m-d H:i:s');
        $order['orderStatus'] = "NONPAYMENT";
        $order['orderType'] = $orderType;
        $order['goodType'] = "MALL";
        $order['body'] = "康泰云端-购买手环";
        Order::create($order);
        if ($orderType == 'WX') {

            $result = NativePay::nativePay($order, "APP");
            $data['createTime'] = $order['createTime'];
            $data['orderNo'] = $order['orderNo'];
            $timestamp = time() . "";
            $signType = "MD5";
            $package = 'prepay_id=' . $result['prepay_id'];
            $nonceStr = nonceStr();
            $model = new WxPayApi();
            $sign['appid'] = env("APPID");
            $sign['partnerid'] = env("MCHID");
            $sign['prepayid'] = $result['prepay_id'];
            $sign['package'] = "Sign=WXPay";
            $sign['noncestr'] = $nonceStr;
            $sign['timestamp'] = $timestamp;
            $resSign = $model->MakeSign($sign);
            //  $resSignRaw = "appId=" . env("APPID") . "&nonceStr=" . $nonceStr . "&package=" . $package . "&signType=" . $signType . "&timeStamp=" . $timestamp . "&key=" . env("WX_KEY");
            //  $resSign = strtoupper(md5($resSignRaw));
            $data['appId'] = env("APPID");
            $data['package'] = $package;
            $data['prepay_id'] = $result['prepay_id'];
            $data['mchId'] = env("MCHID");
            $data['paySign'] = $resSign;
            $data['nonceStr'] = $nonceStr;
            $data['signType'] = $signType;
            $data['timeStamp'] = $timestamp;
            return $this->apiResponse($data);
        }else{
            $order['totalPrice']  = $order['totalPrice'] /100;
            $order['title'] = $order['goodTitle'];
            $ali = new AliApp();
            $result =  $ali->pay($order);
            $data['ali'] = $result;
            $data['orderNo'] = $order['orderNo'];
            return $this->apiResponse($data);
        }
    }

    public function orderUser(Request $request)
    {
        $userId = $request->USERID;
        $amount = $request->amount;
        $orderType = $request->orderType ? $request->orderType : "WX";
        $remark = $request->remark;

        if (!$amount || !$orderType) {
            return $this->apiResponse('', config('errorCode.INVALID_REQ_PARAMS'));
        }
        $orderStatus = Order::where('userId',$userId)
            ->where(['goodType'=>"USER"])
            ->whereNotIn('orderStatus',["CANCEL"])->first();
        $setting = Setting::find(1);
        $userPrice = $setting['userPrice'];
        $reUserPrice = $setting['reUserPrice'];

        if($orderStatus){
            $totalPrice = $reUserPrice * $amount;
            $goodPrice = $reUserPrice;
        }else{
            $subAmount = $amount - 1;
            $totalPrice =$userPrice + $reUserPrice * $subAmount;
            $goodPrice = $userPrice;
        }
        $order['orderNo'] = getOrderSn("");
        $order['remark'] = $remark;
        $order['goodIcon'] = $userId;
        $order['userId'] = $userId;
        $order['goodIcon'] = "https://kangtaiyunduan.oss-cn-beijing.aliyuncs.com/e68b476466a3dde4e38855a259647bc3.png";
        $order['goodTitle'] = "开通会员权限";
        $order['goodPrice'] = $goodPrice;
        $order['totalPrice'] =$totalPrice;
        $order['amount'] = $amount;
        $order['createTime'] = date('Y-m-d H:i:s');
        $order['orderStatus'] = "NONPAYMENT";
        $order['orderType'] = $orderType;
        $order['goodType'] = "USER";
        $order['body'] = "康泰云端-" . $order['goodTitle'];
        Order::create($order);
        if ($orderType == 'WX') {

            $result = NativePay::nativePay($order, "APP");
            $data['createTime'] = $order['createTime'];
            $data['orderNo'] = $order['orderNo'];
            $timestamp = time() . "";
            $signType = "MD5";
            $package = 'prepay_id=' . $result['prepay_id'];
            $nonceStr = nonceStr();
            $model = new WxPayApi();
            $sign['appid'] = env("APPID");
            $sign['partnerid'] = env("MCHID");
            $sign['prepayid'] = $result['prepay_id'];
            $sign['package'] = "Sign=WXPay";
            $sign['noncestr'] = $nonceStr;
            $sign['timestamp'] = $timestamp;
            $resSign = $model->MakeSign($sign);
            $data['appId'] = env("APPID");
            $data['package'] = $package;
            $data['prepay_id'] = $result['prepay_id'];
            $data['mchId'] = env("MCHID");
            $data['paySign'] = $resSign;
            $data['nonceStr'] = $nonceStr;
            $data['signType'] = $signType;
            $data['timeStamp'] = $timestamp;
            return $this->apiResponse($data);
        }else{
            $order['totalPrice']  = $totalPrice / 100;
            $order['title'] =  $order['goodTitle'];
            $ali = new AliApp();
            $result =  $ali->pay($order);
            $data['ali'] = $result;
            $data['orderNo'] = $order['orderNo'];
            return $this->apiResponse($data);
        }
    }


    public function h5Order(Request $request)
    {
        $accessToken = $request->accessToken;
        $amount = $request->amount;
        $orderType = "WX";
        $openid = $request->openid;
        if (!$amount || !$orderType || !$openid) {
            return $this->apiResponse('', config('errorCode.INVALID_REQ_PARAMS'));
        }
        $user = User::where('accessToken', $accessToken)->first();
        if (!$user) {
            return $this->apiResponse('', config('errorCode.USER_NOT_USER'));
        }
        $userId = $user['userId'];
        $orderStatus = Order::where('userId',$userId)   ->where(['goodType'=>"USER"])  ->whereNotIn('orderStatus',["CANCEL"])->first();
        $setting = Setting::find(1);
        $userPrice = $setting['userPrice'];
        $reUserPrice = $setting['reUserPrice'];
        if($orderStatus){
            $totalPrice = $reUserPrice * $amount;
            $goodPrice = $reUserPrice;
        }else{
            $subAmount = $amount - 1;
            $totalPrice =$userPrice + $reUserPrice * $subAmount;
            $goodPrice = $userPrice;
        }


        $order['orderNo'] = getOrderSn("");
        $order['remark'] = "";
        $order['userId'] = $userId;
        $order['goodIcon'] = "https://kangtaiyunduan.oss-cn-beijing.aliyuncs.com/e68b476466a3dde4e38855a259647bc3.png";
        $order['goodTitle'] = "开通会员权限";
        $order['goodPrice'] = $goodPrice;
        $order['totalPrice'] =$totalPrice;
        $order['amount'] = $amount;
        $order['createTime'] = date('Y-m-d H:i:s');
        $order['orderStatus'] = "NONPAYMENT";
        $order['orderType'] = $orderType;
        $order['goodType'] = "USER";
        $order['body'] = "康泰云端-开通会员权限";
        Order::create($order);
        if ($orderType == 'WX') {
            $order['openId'] = $openid;


            $result = NativePay::nativePayH5($order, "JSAPI");
            $data['createTime'] = $order['createTime'];
            $data['orderNo'] = $order['orderNo'];

            //再次签名，给前端返回
            $timestamp = time();
            $signType = "MD5";
            $package = 'prepay_id=' . $result['prepay_id'];
            $nonceStr = nonceStr();
            $resSignRaw = "appId=" . env("WX_APPID") . "&nonceStr=" . $nonceStr . "&package=" . $package . "&signType=" . $signType . "&timeStamp=" . $timestamp . "&key=" . env("WX_KEY");
            $resSign = md5($resSignRaw);
            $responseOrder['appId'] = env("WX_APPID");
            $responseOrder['package'] = $package;
            $responseOrder['paySign'] = $resSign;
            $responseOrder['nonceStr'] = $nonceStr;
            $responseOrder['signType'] = $signType;
            $responseOrder['timeStamp'] = $timestamp;
            return $this->apiResponse($responseOrder);
        }
    }

    public function pay(Request $request)
    {
        $orderNo = $request->orderNo;
        $orderType = $request->orderType ? $request->orderType : "WX";
        if (!$orderNo || !$orderType) {
            return $this->apiResponse('', config('errorCode.INVALID_REQ_PARAMS'));
        }
        Order::where('orderNo', $orderNo)->update(['orderType' => $orderType]);
        $order = Order::where('orderNo', $orderNo)->first();
        if (!$order) {
            return $this->apiResponse('', config('errorCode.INVALID_REQ_PARAMS'));
        }
        if ($orderType == 'WX') {
            $result = NativePay::nativePay($order, "APP");
            $data['createTime'] = $order['createTime'];
            $data['orderNo'] = $order['orderNo'];
            $timestamp = time() . "";
            $signType = "MD5";
            $package = 'prepay_id=' . $result['prepay_id'];
            $nonceStr = nonceStr();
            $model = new WxPayApi();
            $sign['appid'] = env("APPID");
            $sign['partnerid'] = env("MCHID");
            $sign['prepayid'] = $result['prepay_id'];
            $sign['package'] = "Sign=WXPay";
            $sign['noncestr'] = $nonceStr;
            $sign['timestamp'] = $timestamp;
            $resSign = $model->MakeSign($sign);
            //  $resSignRaw = "appId=" . env("APPID") . "&nonceStr=" . $nonceStr . "&package=" . $package . "&signType=" . $signType . "&timeStamp=" . $timestamp . "&key=" . env("WX_KEY");
            //  $resSign = strtoupper(md5($resSignRaw));
            $data['appId'] = env("APPID");
            $data['package'] = $package;
            $data['prepay_id'] = $result['prepay_id'];
            $data['mchId'] = env("MCHID");
            $data['paySign'] = $resSign;
            $data['nonceStr'] = $nonceStr;
            $data['signType'] = $signType;
            $data['timeStamp'] = $timestamp;
            return $this->apiResponse($data);
        }else{
            $order['totalPrice']  = $order['totalPrice'] /100;
            $order['title'] =  $order['goodTitle'];
            $ali = new AliApp();
            $result =  $ali->pay($order);
            $data['ali'] = $result;
            $data['orderNo'] = $order['orderNo'];
            return $this->apiResponse($data);
        }
    }

    public function orderAddress(Request $request)
    {
        $orderNo = $request->orderNo;
        $userId = $request->USERID;
        $addressId = $request->addressId;
        $address = Address::find($addressId);
        if (!$address) {
            return $this->apiResponse('', config('errorCode.NOT_ADDRESS'));
        }
        $order['reciverName'] = $address['reciverName'];
        $order['phone'] = $address['phone'];
        $order['province'] = $address['province'];
        $order['city'] = $address['city'];
        $order['area'] = $address['area'];
        $order['detail'] = $address['detail'];
        $order['orderStatus'] = "WAITDELIVER";
        Order::where('orderNo', $orderNo)->update($order);
        return $this->apiResponse(null);
    }

    public function orderList(Request $request)
    {
        $pageSize = $request->pageSize ? $request->pageSize : 20;
        $userId = $request->USERID;
        $good = Commodity::find(1);
        $afterSalePhone = $good['afterSalePhone'];
        $data = Order::where('userId', $userId)->orderByDesc('createTime')->paginate($pageSize)->toArray();
        foreach ($data['data'] as &$value) {
            $value['afterSalePhone'] = $afterSalePhone;
        }
        return $this->apiResponse($data['data']);
    }

    public function orderContent($orderNo)
    {
        $data = Order::where('orderNo', $orderNo)->first();
        $good = Commodity::find(1);
        if ($data) {
            $data['afterSalePhone'] = $good['afterSalePhone'];
        }
        return $this->apiResponse($data);
    }

    /**
     * 确认收货
     * @param $orderNo
     * @return \Illuminate\Http\JsonResponse
     */
    public function update(Request $request)
    {
        $orderNo = $request->orderNo;
        $status = Order::where(['orderNo' => $orderNo, 'orderStatus' => 'WAITRECEIVE'])->update(['orderStatus' => 'ORDERFINISH']);
        if (!$status) {
            return $this->apiResponse('', config('errorCode.ORDER_DELIVER_FAILED'));
        }
        return $this->apiResponse(null);
    }

    public function cancel(Request $request)
    {
        $orderNo = $request->orderNo;
        $order = Order::where('orderNo', $orderNo)->first();

        if ($order['orderStatus'] == "NONPAYMENT") {
            Order::where(['orderNo' => $orderNo, 'orderStatus' => 'NONPAYMENT'])->update(['orderStatus' => 'CANCEL']);
        } else if ($order['orderStatus'] == "WAITDELIVER") {
            //退款
            $result['orderNo'] = $order['orderNo'];
            $result['refundNo'] = "R" . $order['orderNo'];
            $result['totalPrice'] = $order['totalPrice'];
            $result['refundPrice'] = $order['totalPrice'];
            if($order['orderType'] == "WX"){
                $model = new Refund();
                $status = $model->refund($result);
            }else{
                $result['totalPrice'] = $order['totalPrice']  / 100;
                $result['refundPrice'] = $order['totalPrice']  / 100;
                $result['refundReason'] = "取消订单";
                $model = new AliApp();
                $status = $model->refund($result);
            }
            if ($status) {
                Order::where(['orderNo' => $orderNo, 'orderStatus' => 'WAITDELIVER'])->update(['orderStatus' => 'CANCEL']);
            } else {
                return $this->apiResponse('', config('errorCode.CANCEL_ORDER_FAILED'));
            }
        } else {
            return $this->apiResponse('', config('errorCode.CANCEL_ORDER_FAILED'));
        }


        return $this->apiResponse(null);
    }


    public function isPayOk(Request $request)
    {
        $orderNo = $request->orderNo;
        $order = Order::where('orderNo', $orderNo)->first();
        $result['status'] = 0;
        //订单状态NONPAYMENT 待付款  、 ORDERFINISH 交易完成  WAITDELIVER 待发货 、WAITRECEIVE 待收货   CANCEL 取消订单、REFUND 已退款
        if ($order) {
            if ($order['orderStatus'] == "WAITDELIVER" || $order['orderStatus'] == "WAITRECEIVE" || $order['orderStatus'] == "ORDERFINISH") {
                $result['status'] = 1;
            }
        }
        return $this->apiResponse($result);
    }


}